<template>
  <div>
    <!--    面包屑 导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    开片视图区域-->
    <el-card>
      <!--      警告区域-->
      <el-alert show-icon title="注意，只允许第三级分类参！" type="warning" :closable="false">
      </el-alert>
      <!--      选择商品分类区域-->
      <el-row class="cat_out">
        <el-col>
          <span>选择商品分类:</span>
          <!--          选择商品分类-->
          <el-cascader
            v-model="selectCatKas"
            :options="catelist"
            :props="cateProse"
            @change="handleChange"
            size="mini"></el-cascader>
        </el-col>
      </el-row>
      <!--      tab页签区域-->
      <el-tabs v-model="activeName" @tab-click="handTableClick">
        <!--        添加动态感情-->
        <el-tab-pane label="动态参数" name="many">
          <!--          添加参数-->
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="adddialogVisible=true">添加参数
          </el-button>
          <!--       动态参数表格-->
          <el-table :data="manyTabaData" border stripe>
            <!--            展开行-->
            <el-table-column label="#" type="expand">
              <template v-slot="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handClose(i,scope.row)">
                  {{ item }}
                </el-tag>
                <!--                输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!--                添加的按钮-->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!--            索引列-->
            <!--            索引列-->
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-eadit" size="mini" @click="showEditDiagle(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini"
                           @click="remverPermes(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!--        添加属性参数面板-->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="adddialogVisible=true">添加属性
          </el-button>
          <el-table :data="onlyTableData" border stripe>
            <!--            展开行-->
            <el-table-column label="#" type="expand">
              <template v-slot="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handClose(i,scope.row)">
                  {{ item }}
                </el-tag>
                <!--                输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!--                添加的按钮-->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!--            索引列-->
            <!--            索引列-->
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="静态属性面板" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-eadit" size="mini" @click="showEditDiagle(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button @click="remverPermes(scope.row.attr_id)" type="danger" icon="el-icon-delete" size="mini">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--          添加属性-->

        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--    田间参数-->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="addDialogClost">
      <el-form ref="addformRef" :model="addform" :rules="addformRules" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="adddialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParms">确 定</el-button>
  </span>
    </el-dialog>
    <!--    修改参数对话框-->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="sEditdialogVisible"
      width="50%"
      @close="editDialogClost">
      <el-form ref="eddformRef" :model="editform" :rules="EditformRules" label-width="100px">
        <el-form-item :label="titleText" prop="atter_name">
          <el-input v-model="editform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="sEditdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="EditParms">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      //商品分类列表
      catelist: [],
      //选择框配置对象
      cateProse: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //双向绑定的数组
      selectCatKas: [],
      //被激活的标签内容
      activeName: 'many',
      // 动态参数的数据
      manyTabaData: [],
      // 静态属性的数据
      onlyTableData: [],
      //控制添加对话框
      adddialogVisible: false,
      addform: {
        attr_name: ''
      },
      // 表单验证对象
      addformRules: {
        attr_name: [
          {
            required: true, message: '请输入参数名称', trigger: 'blur'
          }
        ]
      },
      //控制修改对话框的显示和隐藏
      sEditdialogVisible: false,
      editform: {},
      //修改表单的验证对象
      EditformRules: {
        attr_name: [
          {
            required: true, message: '请输入参数名称', trigger: 'blur'
          }
        ]
      },
      //控制按钮和文本框的切花显示
      inputVisible: false,
      //文本框中输入的内容
      inputValue: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const {data: res} = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error("数据获取失败")
      }
      this.catelist = res.data
      console.log(this.catelist)
    },
    //选择项变化会触发
    handleChange() {
      this.getParamsData()
    },
    //tab页签点击时间的处理函数
    handTableClick() {
      this.getParamsData()
    },
    //获取参数的列表
    async getParamsData() {
//证明选中的不是三级分类
      if (this.selectCatKas.length !== 3) {
        this.selectCatKas = []
        this.manyTabaData = []
        this.onlyTableData = []
        return
      }
      //  根据所选分类的id，和当前所处面板获取对应的参数
      const {data: res} = await this.$http.get(`categories/${this.catId}/attributes`,
        {params: {sel: this.activeName}})
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //控制文本框的显示和隐藏
        item.inputVisible = false
        //文本框中输入
        item.saveTagInput = ''
      })
      if (this.activeName === 'many') {
        this.manyTabaData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    //监听添加对话框的关闭事件
    addDialogClost() {
      this.$refs.addformRef.resetFields()
    },
    //点击按钮添加参数
    addParms() {
      this.$refs.addformRef.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.post(`categories/${this.catId}/attributes`, {
          attr_name: this.addform.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error("添加参数失败")
        }
        this.$message.success('添加参数成功')
        this.adddialogVisible = false
        this.getCateList()
      })
    },
    //展示修改的对话框
    async showEditDiagle(attr_id) {
      const {data: res} = await this.$http.get(
        `categories/${this.catId}/attributes/${attr_id}`,
        {
          params: {attr_sel: this.activeName}
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败")
      }
      this.editform = res.data
      this.sEditdialogVisible = true
    },
    //修改重置表单
    editDialogClost() {
      this.$refs.eddformRef.resetFields()
    },
    //点击按钮修改参数
    EditParms() {
      this.$refs.eddformRef.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.put(`categories/${this.catId}/attributes/${this.editform.attr_id}`,
          {attr_name: this.editform.attr_name, attr_sel: this.activeName})
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败")
        }
        this.$message.success("修改成功")
        this.getParamsData()
        this.sEditdialogVisible = false
      })

    },
    //更具id删除对象的id
    async remverPermes(attrId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 用户取消了删除的操作
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }

      // 删除的业务逻辑
      const {data: res} = await this.$http.delete(
        `categories/${this.catId}/attributes/${attrId}`
      )

      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败！')
      }

      this.$message.success('删除参数成功！')
      this.getParamsData()
    },
    //文本失去焦点
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //如果没有return则需要后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      //  发起网络请求保存这一次的数据
      this.svaerAttr(row)
    },
    // 姜对attr的操作保存到数据库
    async svaerAttr(row) {
      const {data: res} = await this.$http.put(`categories/${this.catId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error("数据参数修改失败")
      }
      this.$message.success("数据参数修改成功!")
    },
    //点击按钮暂时文本输入库
    showInput(row) {
      row.inputVisible = true
      //让文本框自己获得焦点
      // $nextTick方法作用当页面的元素被从新渲染之后才会执行这行代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.svaerAttr(row)
    }

  },
  computed: {
    //如果被禁用则返回true否则返回false
    isBtnDisabled() {
      if (this.selectCatKas.length !== 3) {
        return true
      }
      return false
    },
    //当前选中的二级id
    catId() {
      if (this.selectCatKas.length === 3) {
        return this.selectCatKas[2]
      }
      return null
    },
    //动态计算标题
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '动态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_out {
  margin: 15px 0;
}

.input-new-tag {
  width: 120px;
}
</style>
